package com.basin.feign.interceptor;

import com.basin.feign.config.Init4FeignLogic;
import com.basin.feign.config.vo.FeignReqSettingsVO;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Map;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
@Slf4j
public class FeignServerInterceptor extends OncePerRequestFilter {
    @Resource
    private Init4FeignLogic feignLogic;

    @Value("${spring.application.name}")
    private String applicationName;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        Map<String, FeignReqSettingsVO> settingsMap = feignLogic.collectFeignReqSettings();
        FeignReqSettingsVO vo = settingsMap.get(applicationName);
        if (vo == null) {
            log.error("Feign server拦截器创建失败：未读取到应用[" + applicationName + "]对应的配置项");
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Feign server拦截器创建失败：未读取到应用[" + applicationName + "]对应的配置项");
            return;
        }
        String authorization = request.getHeader("Authorization");
        boolean ok = feignLogic.validAuthorization(vo, authorization);
        if (!ok) {
            log.error("Feign server拦截器拒绝访问：应用[" + applicationName + "]未通过请求认证");
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Feign server拦截器拒绝访问：应用[" + applicationName + "]未通过请求认证");
            return;
        }
        filterChain.doFilter(request, response);
    }
}
